const path = require('path');
const fs = require('fs-extra')
module.exports = app => {
    app.ws('/videoBuffer', async (ws, req) => {
        const fileIO = require('./utils/fileIO');
        ws.on('message', async (message) => {
            if(path.extname(message) !== '.mp4'){
                const res = fs.readFileSync(message)
                ws.send(res, { binary: true });
            }
            console.log(message);
            const res = await fileIO.fetchVideoBuffer(message)
            ws.send(res.buffer, { binary: true });
        })
    });
    app.ws('/controlCamera', async (ws, req) => {
        let isMoving = false;
        let device = null, base = null, control = null, ProfileToken = null;
        ws.on('message', async function (message) {
            if (isMoving) return { type: 'error', message: '正在移动中，请稍后再试！' };
            console.log('Received message:', message);
            try {
                const parseData = JSON.parse(message);
                console.log(parseData);
                if (parseData.type === 'move' && device) {
                    let { x, y, z, speed } = parseData.data;
                    if (parseData.method === 'continuous') {
                        x = x / 1.3;
                        y = y / 1.1;
                        z = z / 1.1;
                    }
                    isMoving = true;
                    control.deviceMove({
                        ProfileToken,
                        orient: { x, y, z },
                        Speed: speed,
                        type: parseData.method,
                    }).then(async (res) => {
                        res.pos = await base.getCurrentPostiton({ ProfileToken });
                        ws.send(JSON.stringify(res));
                        isMoving = false;
                        console.log(res);
                    }).catch((err) => {
                        console.log(err);
                    });
                } else if (parseData.type === 'conn' && !device) {
                    const mOnvif = require('./utils/onvif');
                    const res = await mOnvif.conn(parseData.config);
                    if (res.type === 'success') {
                        device = res.device;
                        base = res.base;
                        control = res.control;
                        ProfileToken = base.getCurrentProfile()['token']
                        ws.send(JSON.stringify({
                            type: 'success',
                            data: {
                                name: base.getInformation(),
                                position: await base.getCurrentPostiton({ ProfileToken })
                            }
                        }));
                    } else if (res.type === 'error') {
                        ws.send(JSON.stringify(res));
                    }
                }
            } catch (error) {

            }
        });
    });

}